package crmdna.api.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.google.api.client.extensions.appengine.datastore.AppEngineDataStoreFactory;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.appengine.api.utils.SystemProperty;

class Utils {

	private static final AppEngineDataStoreFactory DATA_STORE_FACTORY = AppEngineDataStoreFactory
			.getDefaultInstance();

	private static final List<String> SCOPES = Arrays.asList(
			"https://www.googleapis.com/auth/userinfo.email");

	private static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();
	private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
		
	static String getRedirectUri(HttpServletRequest req) {
		GenericUrl url = new GenericUrl(req.getRequestURL().toString());
		url.setRawPath("/google-oauth2callback");
		return url.build();
	}

	static GoogleAuthorizationCodeFlow newFlow() throws IOException {
		return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
				JSON_FACTORY, getClientId(), getClientSecret(), SCOPES)
				.setDataStoreFactory(DATA_STORE_FACTORY)
				.build();
	}
	
	private static String getClientId() {
		if(SystemProperty.applicationId.get() == "ishacrmserver") {
			return "429804891913.apps.googleusercontent.com";
		}
		return "760145670838-gt0r79qfoege1ogcd8q5qvmgbjoks2ph.apps.googleusercontent.com"; //ishacrmserverdev
	}

	private static String getClientSecret() {
		if(SystemProperty.applicationId.get() == "ishacrmserver") {
			return "k2OtHkhgbq2LzgGlyhBp2lq9";
		}
		
		return "5ppGUXzTufF2g2xQd5gxJLe3"; //ishacrmserverdev
	}

	static IOException wrappedIOException(IOException e) {
		if (e.getClass() == IOException.class) {
			return e;
		}
		return new IOException(e.getMessage());
	}

	private Utils() {
	}
}